package com.sky.service.impl;

import com.aliyun.oss.common.utils.StringUtils;
import com.github.pagehelper.Page;
import com.sky.entity.OrderDetail;
import com.sky.mapper.OrderDetailMapper;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import com.sun.org.apache.xpath.internal.operations.String;
import org.apache.poi.util.StringUtil;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.Servlet;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.List;

@Service
public class ReportServiceImpl implements ReportService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private WorkspaceService workspaceService;
    /**
     * 按照日期统计营业额
     *
     * @param begin
     * @param end
     * @return
     */
    @Override
    public TurnoverReportVO turnoverStatistics(LocalDate begin, LocalDate end) {
        List<TurnoverVO> turnoverVOs=orderMapper.getTurnover(begin,end);
        StringBuilder order_dates=new StringBuilder();
        StringBuilder order_turnover=new StringBuilder();
        LocalDate tempDate=begin;
        if(turnoverVOs!=null && !turnoverVOs.isEmpty()) {
            for (TurnoverVO turnoverVO : turnoverVOs) {
                while(!tempDate.isEqual(turnoverVO.getOrderDate())){
                    order_dates.append(tempDate);
                    order_turnover.append(0);
                    order_dates.append(",");
                    order_turnover.append(",");
                    tempDate= tempDate.plusDays(1);
                }
                order_dates.append(turnoverVO.getOrderDate().toString());
                order_turnover.append(turnoverVO.getTurnover());
                order_dates.append(",");
                order_turnover.append(",");
                tempDate=tempDate.plusDays(1);
            }
            order_dates.deleteCharAt(order_dates.length()-1);
            order_turnover.deleteCharAt(order_turnover.length()-1);
        }
        return new TurnoverReportVO(order_dates.toString(),order_turnover.toString());
    }

    /**
     * 按照日期统计新增用户以及总的用户数
     * @param begin
     * @param end
     * @return
     */
    @Override
    public UserReportVO getUserStatistics(LocalDate begin, LocalDate end) {
        List<UserVO> userVOs=userMapper.getUserAddition(begin,end);
        StringBuilder dateList=new StringBuilder();
        StringBuilder additionList=new StringBuilder();
        StringBuilder totalSumList=new StringBuilder();
        LocalDate tempDate=begin;
        Long baseAmount=userMapper.cntUserBefore(begin);
        if(userVOs!=null && !userVOs.isEmpty()){
            for(UserVO userVO:userVOs){
                while(!tempDate.equals(userVO.getCreateDate())){
                    dateList.append(tempDate);
                    additionList.append(0);
                    totalSumList.append(0);
                    dateList.append(",");
                    additionList.append(",");
                    totalSumList.append(",");
                    tempDate=tempDate.plusDays(1);
                }
                dateList.append(userVO.getCreateDate());
                additionList.append(userVO.getNewAddition());
                baseAmount+=userVO.getNewAddition();
                totalSumList.append(baseAmount);
                dateList.append(",");
                additionList.append(",");
                totalSumList.append(",");
                tempDate=tempDate.plusDays(1);
            }
            dateList.deleteCharAt(dateList.length()-1);
            additionList.deleteCharAt(additionList.length()-1);
            totalSumList.deleteCharAt(totalSumList.length()-1);
        }
        return new UserReportVO(dateList.toString(),totalSumList.toString(),additionList.toString());
    }

    /**
     * 获取订单数据
     * @param begin
     * @param end
     * @return
     */
    @Override
    public OrderReportVO getOrderStatistics(LocalDate begin, LocalDate end) {
        List<OrderPerDateVO> orderPerDateVOs=orderMapper.getOrderPerDate(begin,end);
        StringBuilder dateList=new StringBuilder();
        StringBuilder orderSumList=new StringBuilder();
        StringBuilder valuedOrderSumList=new StringBuilder();
        Long totalSum=0L;
        Long totalValued=0L;
        LocalDate tempDate=begin;
        if(orderPerDateVOs!=null && !orderPerDateVOs.isEmpty()){
            for(OrderPerDateVO orderPerDateVO:orderPerDateVOs){
                while(!tempDate.equals(orderPerDateVO.getOrderDate())){
                    dateList.append(tempDate);
                    orderSumList.append(0);
                    valuedOrderSumList.append(0);
                    dateList.append(",");
                    orderSumList.append(",");
                    valuedOrderSumList.append(",");
                    tempDate=tempDate.plusDays(1);
                }
                dateList.append(orderPerDateVO.getOrderDate());
                orderSumList.append(orderPerDateVO.getOrderSum());
                valuedOrderSumList.append(orderPerDateVO.getValuedOrderSum());
                totalSum+=orderPerDateVO.getOrderSum();
                totalValued+=orderPerDateVO.getValuedOrderSum();
                dateList.append(",");
                orderSumList.append(",");
                valuedOrderSumList.append(",");
                tempDate=tempDate.plusDays(1);
            }
            dateList.deleteCharAt(dateList.length()-1);
            orderSumList.deleteCharAt(orderSumList.length()-1);
            valuedOrderSumList.deleteCharAt(valuedOrderSumList.length()-1);
        }
        Double completedRate=totalSum==0?0.0:((double) totalValued) / totalSum;
        return new OrderReportVO(dateList.toString(),
                orderSumList.toString(),
                valuedOrderSumList.toString(),
                totalSum,totalValued,
                completedRate);
    }

    /**
     * 查询销量排名前十
     * @param begin
     * @param end
     * @return
     */
    @Override
    public SalesTop10ReportVO getTop10Statistics(LocalDate begin, LocalDate end) {
        List<SalesTop10VO> salesTop10VOs=orderDetailMapper.getSalesTop10(begin,end);
        StringBuilder nameList=new StringBuilder();
        StringBuilder sumList=new StringBuilder();
        if(salesTop10VOs!=null && !salesTop10VOs.isEmpty()){
            for(SalesTop10VO salesTop10VO:salesTop10VOs){
                nameList.append(salesTop10VO.getName());
                sumList.append(salesTop10VO.getSum());
                nameList.append(",");
                sumList.append(",");
            }
            nameList.deleteCharAt(nameList.length()-1);
            sumList.deleteCharAt(sumList.length()-1);
        }
        return new SalesTop10ReportVO(nameList.toString(),sumList.toString());
    }

    /**
     * 报表数据导出
     * @param response
     */
    @Override
    public void exportBusinessData(HttpServletResponse response) {
        // 查询数据库，获取报表数据（近三十天）
        LocalDate begin=LocalDate.now().minusDays(30);
        LocalDate end=LocalDate.now();
        LocalDate temp=begin;
        Double totalTurnover=0.0;
        Integer valuedOrders=0;
        Integer totalOrders=0;
        Integer userAddition=0;
        // 通过POI将数据写入excel文件
        InputStream inputStream=this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");
        try {
            XSSFWorkbook excel = new XSSFWorkbook(inputStream); // 基于模板文件创建新的excel文件
            // 填充数据
            XSSFSheet sheet=excel.getSheet("Sheet1"); // 获取sheet页
            sheet.getRow(1).getCell(1).setCellValue("时间："+begin+"-"+end.plusDays(-1));
            XSSFRow row;
            for(int i=0;i<30;i++){
                BusinessDataVO businessDataVO=workspaceService.getBusinessData(temp);
                totalTurnover+=businessDataVO.getTurnover();
                valuedOrders+=businessDataVO.getValidOrderCount();
                userAddition+=businessDataVO.getNewUsers();
                row=sheet.getRow(7+i);
                row.getCell(1).setCellValue(temp.toString());
                row.getCell(2).setCellValue(businessDataVO.getTurnover());
                row.getCell(3).setCellValue(businessDataVO.getValidOrderCount());
                row.getCell(4).setCellValue(businessDataVO.getOrderCompletionRate());
                row.getCell(5).setCellValue(businessDataVO.getUnitPrice());
                row.getCell(6).setCellValue(businessDataVO.getNewUsers());
                temp=temp.plusDays(1);
            }
            row=sheet.getRow(3);
            row.getCell(2).setCellValue(totalTurnover);
            row.getCell(4).setCellValue(0.0);
            row.getCell(6).setCellValue(userAddition);
            row=sheet.getRow(4);
            row.getCell(2).setCellValue(valuedOrders);
            row.getCell(4).setCellValue(totalTurnover/valuedOrders);
            // 通过输出流将excel文件下载到客户端浏览器
            ServletOutputStream outputStream=response.getOutputStream();
            excel.write(outputStream);

            // 关闭资源
            outputStream.close();
            excel.close();
        }catch(IOException ex){
            ex.printStackTrace();
        }
    }
}
